package com.saver.view;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.github.mikephil.charting.utils.Utils;
import com.saver.R;
import com.saver.core.persistence.DBManager;
import com.saver.core.persistence.TransaccionViewSQLite;
import com.saver.core.processor.util.Util;
import com.saver.core.util.CommonUtil;
import com.saver.core.util.Constantes;
import com.saver.service.SMSBroadcastReceiver;
import com.saver.view.adapter.TransactionListAdapter;
import com.saver.view.dialog.EditTransactionDialog;
import com.saver.view.dialog.RefreshActivity;
import com.saver.view.gui.FragmentSupport;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HGonzales.
 */
public class TransactionListActivity extends Activity implements AdapterView.OnItemClickListener, RefreshActivity {

    public static final String KEY_CATEGORY_NAME = "category_name";
    public static final String KEY_INSTITUTION = "institution";
    public static final String KEY_EVENT_DATE = "event_date";
    public static final String KEY_MONEY_IMPORT = "money_import";
    public static final String KEY_ICON_CATEGORY = "icon_category";
    public static final String KEY_COLOR = "color";
    public static final String KEY_TRANSACTION = "transaction_id";

    TransaccionViewSQLite transaccionViewSQLite;
    List<TransaccionView> listaTransaccion = new ArrayList<TransaccionView>();
    String idBanco;
    Integer tipoConsulta;
    Integer anio;
    Integer mes;
    Integer dia;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iniciar();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        actualizarVisualizado();
    }

    public void iniciar() {
        setContentView(R.layout.activity_list_main);
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        createTransaction();
        Utils.init(getResources());

        DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
        ArrayList<Map<String, String>> dataList = new ArrayList<Map<String, String>>();

        String string;
        String eventDate;
        for (TransaccionView transaccion : listaTransaccion) {
            eventDate = df.format(transaccion.getFechaTransaccion());
            Map<String, String> data = new HashMap<String, String>();
            data.put(KEY_CATEGORY_NAME, (string = transaccion.getNombreCategoria()) != null ? string : "");
            String detalle = transaccion.getReferencia();
            if (Util.esVacio(detalle)) {
                detalle = transaccion.getNombreEstablecimiento();
                if(Util.esVacio(detalle)){
                	detalle = transaccion.getNombreCategoriaEquiv();
                }
            }
            data.put(KEY_INSTITUTION, detalle);
            data.put(KEY_EVENT_DATE, eventDate);
            data.put(KEY_MONEY_IMPORT, CommonUtil.formatCurrency(transaccion.getMonto()));
            data.put(KEY_ICON_CATEGORY, transaccion.getIcono());
            data.put(KEY_COLOR, transaccion.getColor());
            data.put(KEY_TRANSACTION, String.valueOf(transaccion.getId()));
            dataList.add(data);
        }

        Bundle intentExtras = getIntent().getExtras();
        if ((Boolean) intentExtras.get(Constantes.VAR_RESET_SMS_COUNT)) {
            //TODO: actualizar estado de la transaccion
            SMSBroadcastReceiver.resetCount();
        }

        ListView listView = (ListView) findViewById(R.id.listViewDetail);
        TransactionListAdapter adapter = new TransactionListAdapter(this, dataList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
    }

    private void createTransaction() {
        transaccionViewSQLite = new TransaccionViewSQLite(this);

        idBanco = (String) getIntent().getExtras().get("idBanco");
        tipoConsulta = getIntent().getExtras().getInt(Constantes.VAR_TIPO_CONSULTA);

        if (tipoConsulta.equals(Constantes.CONSULTA_X_ANIO)) {
            anio = getIntent().getExtras().getInt(Constantes.VAR_ANIO);
            listaTransaccion = transaccionViewSQLite.listarTransaccionesXCategoria(Integer.parseInt(idBanco), anio);
        } else if (tipoConsulta.equals(Constantes.CONSULTA_X_MES)) {
            anio = getIntent().getExtras().getInt(Constantes.VAR_ANIO);
            mes = getIntent().getExtras().getInt(Constantes.VAR_MES);
            listaTransaccion = transaccionViewSQLite.listarTransaccionesXCategoria(Integer.parseInt(idBanco), anio, mes);
        } else if (tipoConsulta.equals(Constantes.CONSULTA_X_DIA)) {
            anio = getIntent().getExtras().getInt(Constantes.VAR_ANIO);
            mes = getIntent().getExtras().getInt(Constantes.VAR_MES);
            dia = getIntent().getExtras().getInt(Constantes.VAR_DIA);
            listaTransaccion = transaccionViewSQLite.listarTransaccionesXCategoria(Integer.parseInt(idBanco), anio, mes, dia);
        } else if (tipoConsulta.equals(Constantes.CONSULTA_X_REVISAR)) {
            listaTransaccion = transaccionViewSQLite.listarTransaccionesXRevisar();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Integer transactionID = Integer.valueOf((String) view.getTag());
        FragmentManager manager = getFragmentManager();
        EditTransactionDialog dialog = new EditTransactionDialog();
        dialog.setParent(this);
        dialog.setTransaccionID(transactionID);
        dialog.show(manager, "Editar Transaccion");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                actualizarVisualizado();
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void actualizarVisualizado() {
        for (TransaccionView transaccion : listaTransaccion) {
            DBManager.transaccionSQLite().actualizarARevisado(transaccion);
        }
    }

    @Override
    public void refresh(Object params) {
        iniciar();
    }

    @Override
    public void reemplazarFragmento(FragmentSupport fragment) {

    }

    @Override
    public void selectedIndex(int position) {

    }
}
